import { exec } from "https://deno.land/x/exec@0.0.5/mod.ts";

function zero(v: number) {
  return v < 10 ? `0${v}` : v.toString();
}

function getFormatDuringTime(start: string, end: string) {
  const startArr = start.split(":");
  const endArr = end.split(":");

  const startSec =
    Number(startArr[0]) * 60 * 60 +
    Number(startArr[1]) * 60 +
    Number(startArr[2]);
  const endSec =
    Number(endArr[0]) * 60 * 60 + Number(endArr[1]) * 60 + Number(endArr[2]);

  let during = Math.abs(endSec - startSec);
  const s = Math.floor(during / 1) % 60;
  during = Math.floor(during / 60);
  const i = during % 60;
  during = Math.floor(during / 60);
  const h = during;
  const result = [zero(h), zero(i), zero(s)];
  return result.join(":");
}

interface IConfig {
  start: string;
  end: string;
  input: string;
  output: string;
}

// ffmpeg -ss 01:07:30 -t 00:46:47 -i "input.mkv" -vcodec copy -acodec copy demo.mkv
async function split(configList: IConfig[], index = 0) {
  const config = configList[index];
  const during = getFormatDuringTime(config.end, config.start);
  const params = [
    "-ss",
    config.start,
    "-t",
    during,
    "-i",
    config.input,
    "-vcodec",
    "copy",
    "-acodec",
    "copy",
    config.output,
  ];
  console.log(`${index + 1}/${configList.length}`);
  console.log("ffmpeg " + params.join(" "));
  const out = await exec("ffmpeg " + params.join(" "));
  console.log(out);
}

const configList = [
  {
    start: "00:00:00",
    end: "00:02:00",
    input: `"input/【内部培训】lightning讲义.mp4"`,
    output: `"input/【内部培训】lightning讲义2.mp4"`,
  },
];
await split(configList);
Deno.exit();
